<template>
  <!-- 增加修改 -->
  <a-drawer width="50%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules" :layout="'horizontal'">
      <a-row :gutter="24">
        <a-col
          :span="24">
          <a-form-model-item label="出库单号" prop="shipmentNumber">
            <a-input v-model="form.shipmentNumber" placeholder="系统生成" disabled/>
          </a-form-model-item>
        </a-col>

      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="加工过程卡" prop="warehouseReceiptId">
            <a-tree-select
              v-model="form.warehouseReceiptId"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="warehouseReceiptDataList"
              placeholder="请选择"
              :replaceFields="replaceFields"
              tree-default-expand-all
              @select="selectWarehouseReceiptId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="零件名称" prop="externalBatchNumber">
            <a-input v-model="form.externalBatchNumber" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>

      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="出库时间" prop="partName" disabled>
            <a-input v-model="form.partName" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col
          :span="12">
          <a-form-model-item label="零件图号" prop="partName" disabled>
            <a-input v-model="form.partName" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>

      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="领用人" prop="useUserId">
            <a-tree-select
              v-model="form.useUserId"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="opeUsers"
              placeholder="请选择"
              :replaceFields="{ children: 'children', title: 'nickName', key: 'id', value: 'id' }"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="24">
          <a-form-model-item label="备注" prop="remark">
            <a-input type="textarea" v-model="form.remark" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider />
      <!-- 交付节点 -->
      <a-row :gutter="24" class="action-bar">
        <a-space>
          <!-- <span>出库明细</span> -->
          <a-button type="primary" class="editable-add-btn" @click="undelete">
            撤回删除
          </a-button>
        </a-space>
      </a-row>

      <a-row :gutter="24">
        <a-table bordered :data-source="form.handleAddWarehouseReceiptItems" :columns="orderNodeListColumns" size="small" :pagination="false">
          <!-- 序号列插槽 -->
          <template slot="indexSlot" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>

          <template slot="testPiece" slot-scope="text, record">
            <a-input :value="text == 0||text=='否'? '否': '是'" @change="e=>handleChange(e.target.value, record, 'testPiece')" disabled/>
          </template>

          <template slot="internalNumber" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'internalNumber')" disabled/>
          </template>

          <template slot="partNumber" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'partNumber')" disabled/>
          </template>

          <template slot="castingNumber" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'castingNumber')" disabled/>
          </template>

          <template slot="partName" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'partName')" disabled/>
          </template>

          <!-- :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" -->
          <template slot="action" slot-scope="text, record">
            <a href="javascript:;" @click="handleDelete(record)" >删除</a>
          </template>
        </a-table>

      </a-row>

      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>

import { listAll } from '@/api/system/user'
import { list as warehouseReceiptList } from '@/api/materials/warehousing'
import { add, getById, update } from '@/api/materials/warehouseShipment'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import { warehouseReceiptItems } from '@/api/baseData/warehouseReceiptItems'
import { mapGetters } from 'vuex'

export default {
  name: 'CreateForm',
  props: {
    deptOptions: {
      type: Array,
      required: true
    }
  },
  components: {
  },
  data () {
    dayjs.extend(customParseFormat)

    return {
      submitLoading: false,
      replaceFields: { children: 'children', title: 'internalBatchNumber', key: 'id', value: 'id' },
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      formTitle: '',
      // 表单参数
      form: {
        shipmentNumber: undefined,
        warehouseReceiptId: undefined,
        partName: undefined,
        externalBatchNumber: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        inventoryQuantity: undefined,
        shipmentQuantity: undefined,
        testQuantity: undefined,
        productionBatchNo: undefined,
        formalQuantity: undefined,
        formalWarehouse: undefined,
        testWarehouse: undefined,
        warehouse: undefined,
        warehouseStorey: undefined,
        remark: undefined,
        wmsName: undefined,
        wmsStorey: undefined,

        handleAddWarehouseReceiptItems: [],
        projectId: undefined,
        type: 1 // 出库
      },
      open: false,
      rules: {

        partName: [
          { required: true, message: '零件名称不能为空', trigger: 'blur' }
        ]
      },
      orderNodeListColumns: [
      {
        title: '序号',
        key: 'index',
        scopedSlots: { customRender: 'indexSlot' }, // 索引从0开始，+1后从1显示
        width: 80,
        align: 'center'
      },
        {
          title: '是否是试刀件',
          dataIndex: 'testPiece',
          ellipsis: true,
          scopedSlots: { customRender: 'testPiece' },
          width: 80
        },
        {
          title: '零件内部编号',
          dataIndex: 'internalNumber',
          scopedSlots: { customRender: 'internalNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '零件号',
          dataIndex: 'partNumber',
          scopedSlots: { customRender: 'partNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '铸件号',
          dataIndex: 'castingNumber',
          scopedSlots: { customRender: 'castingNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '零件名称',
          dataIndex: 'partName',
          scopedSlots: { customRender: 'partName' },
          ellipsis: true,
          width: 80
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 50
        }

      ],
      partPlanIncomingList: [],
      inventoryItemList: [],
      nametestPieceEnum: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      warehouseReceiptDataList: [],
      deleteList: [],
      opeUsers: []
    }
  },
  filters: {
  },
  created () {
    this.init()
  },
  computed: {
    ...mapGetters([
      'avatar',
      'nickname'
    ])
  },
  watch: {
    'form.handleAddWarehouseReceiptItems': {
      handler (newItems) {
        console.log('数组内对象属性变化', newItems)
        var testNum = 0
        var num = 0
        newItems.forEach((element, index) => {
          if (element.nametestPiece === 1) {
            element.internalNumber = 'S' + ++testNum
          } else {
            element.internalNumber = 'Z' + ++num
          }
        })

        this.form.formalQuantity = num
        this.form.testQuantity = testNum
        this.form.shipmentQuantity = (num + testNum)
        this.form.sykcs = this.form.inventoryQuantity - this.form.shipmentQuantity
      },
      deep: true // 深度监听
    }
  },
  methods: {
    dayjs, // 将 dayjs 作为方法暴露给模板
    init () {
      this.getWarehouseReceiptList()
      this.getOperator()
    },
    getOperator () {
      listAll().then(res => {
        this.opeUsers = res.data
      })
    },
    // 加载毛坯入库数据
    getWarehouseReceiptList () {
      warehouseReceiptList().then(res => {
        this.warehouseReceiptDataList = res.data
        console.info(res, 'getWarehouseReceiptList', this.warehouseReceiptDataList)
      })
    },
    // 选择毛坯入库单
    selectWarehouseReceiptId (value) {
      this.form.warehouseReceiptId = value
      const warehouseReceipt = this.warehouseReceiptDataList.filter(item => item.id === this.form.warehouseReceiptId)[0]
      this.form = {
        ...this.form,
        externalBatchNumber: warehouseReceipt.externalBatchNumber,
        internalBatchNumber: warehouseReceipt.internalBatchNumber,
        partName: warehouseReceipt.partName,
        partDrawingNo: warehouseReceipt.partDrawingNo,
        partAbbreviation: warehouseReceipt.partAbbreviation,
        inventoryQuantity: warehouseReceipt.totalQuantity,
        wmsName: warehouseReceipt.wmsName,
        wmsStorey: warehouseReceipt.wmsStorey
      }
      this.getwarehouseReceiptItems({
        partDrawingNo: this.form.partDrawingNo,
        status: 0
      })
    },
    // 加载毛坯出库明细
    getwarehouseReceiptItems (query) {
      warehouseReceiptItems(query).then(res => {
        console.info(res, 'partDrawingNo')
        this.form.handleAddWarehouseReceiptItems = res.data
      })
    },
    // 删除
    handleDelete (record) {
      this.form.handleAddWarehouseReceiptItems = this.form.handleAddWarehouseReceiptItems.filter(item => item.id !== record.id)
      this.deleteList.push(record)
    },
    // 设置table form 值
    handleChange (e, info, ee) {
      console.info(e, info, ee)
      info[ee] = e
    },
    // 撤回删除
    undelete () {
      if (this.deleteList.length > 0) {
        console.info(this.deleteList)
        const del = this.deleteList.pop()
        console.info(del)
        this.form.handleAddWarehouseReceiptItems.push(del)
      }
    },
    // 选择外部批次号
    selectExternalBatchNumber (selectedKeys, info) {
      console.info((this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]))
      this.form.partDrawingNo = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).partDrawingNo
      this.form.externalBatchNumber = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).batchNumber
    },
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        shipmentNumber: undefined,
        warehouseReceiptId: undefined,
        partName: undefined,
        externalBatchNumber: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        inventoryQuantity: undefined,
        shipmentQuantity: undefined,
        testQuantity: undefined,
        productionBatchNo: undefined,
        formalQuantity: undefined,
        formalWarehouse: undefined,
        testWarehouse: undefined,
        warehouse: undefined,
        warehouseStorey: undefined,
        remark: undefined,
        useUserName: undefined,
        useUserId: undefined,

        handleAddWarehouseReceiptItems: [],
        projectId: this.selectProjectId,
        type: 1 // 出库
      }
    },
     /** 新增按钮操作 */
    handleAdd (selectProjectId) {
      console.info('handleAdd', selectProjectId)
      if (!selectProjectId) {
        this.$message.error(
                '请先选择项目',
                3
              )
        return
      }
      this.reset()
      this.$emit('select-tree')
      this.open = true
      this.formTitle = '工装出库单'
      this.selectProjectId = selectProjectId
      this.form = {
        shipmentNumber: undefined,
        warehouseReceiptId: undefined,
        partName: undefined,
        externalBatchNumber: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        inventoryQuantity: undefined,
        shipmentQuantity: undefined,
        testQuantity: undefined,
        productionBatchNo: undefined,
        formalQuantity: undefined,
        formalWarehouse: undefined,
        testWarehouse: undefined,
        warehouse: undefined,
        warehouseStorey: undefined,
        remark: undefined,
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        handleAddWarehouseReceiptItems: [],
        projectId: selectProjectId,
        type: 1 // 出库
      }

      this.init()
    },
    /** 修改按钮操作 */
    handleUpdate (row, ids) {
      this.reset()
      this.$emit('select-tree')

      getById(row.id).then(res => {
        this.form = res.data
         this.open = true
        this.formTitle = '修改毛批出库单'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id !== undefined) {
            update(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            add(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
